import { _decorator, assetManager, Component, ImageAsset, Node, resources, UITransform } from 'cc';
import { HTMLRichText } from '../../../extensions/cc-feather/assets/src';
import { EDITOR } from 'cc/env';
const { ccclass, property } = _decorator;

@ccclass('Demo')
export class Demo extends HTMLRichText {
    @property(Node)
    emoji: Node;

    start() {
        if (EDITOR) {
            assetManager.loadAny<ImageAsset>('99ce2773-c288-4d67-9868-27bb8d5e9ea9', (err, img) => {
                if (err) return console.error(err);
                super.start();
            });
        } else {
            resources.load('image/gold', ImageAsset, (err, img) => {
                if (err) return console.error(err);
                super.start();
            });
        }
    }

    placeEmojiHere(x: number, y: number, h: number, size: [number, number]) {
        // canvas 和 ccc 的坐标系不同，所以要转换一下。
        // 这里就不写了，用现成的。这个 Spine 的基线似乎有点高，还需要调整一下。
        const { width, height } = this._canvas;
        const [left, top] = this._parser.style.margin;
        const [cw, ch] = size;
        let offset = { x: -width / 2, y: -height / 2 };
        let origin = { x: x + left, y: height - y - top };
        let transform = this.emoji.getComponent(UITransform)!;
        let { width: pw, height: ph } = transform;
        let { x: ax, y: ay } = transform.anchorPoint;
        let pos = {
            x: origin.x + offset.x + cw / 2 + (0.5 - ax) * pw,
            y: origin.y + offset.y + ch / 2 + (0.5 - ay) * ph - 177,
        };
        this.emoji.setPosition(pos.x, pos.y, 0);
    }
}
